<template>
  <div class="app-container">
    <el-form ref="form"
             :model="queryForm"
             label-width="80px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="司机姓名"
                        label-width="90px">
            <el-input v-model="queryForm.driverName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="身份证号">
            <el-input v-model="queryForm.id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="作业状态">
            <el-select v-model="queryForm.taskStatus"
                       placeholder="">
              <el-option v-for="item in workStatus"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="绑定类型">
            <el-select v-model="queryForm.bindType"
                       placeholder="">
              <el-option v-for="item in bindType"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item label="绑定状态"
                        label-width="90px">
            <el-select v-model="queryForm.bindStatus"
                       placeholder="">
              <el-option v-for="item in bindStatus"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="PCC卡号">
            <el-input v-model="queryForm.pcc"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="车牌">
            <span style="width: 80px; float: left;">
              <el-select v-model="queryForm.vehicleColor"
                         placeholder="">
                <el-option v-for="item in vehicleColor"
                           :key="item.id"
                           :label="item.value"
                           :value="item.id">
                </el-option>
              </el-select>
            </span>
            <span style="width: 70px; float: left; margin-left: 10px;">
              <el-input v-model="queryForm.vehiclePy"></el-input>
            </span>
            <span style="width: 140px; float: left; margin-left: 10px;">
              <el-input v-model="queryForm.vehicleKey"></el-input>
            </span>
            <!-- <span style="width: 50px; float: left; margin-left: 10px;">
              <el-select style="width:100px"
                         v-model="queryForm.vehicleSuf"
                         placeholder="">
                <el-option v-for="item in vehicleSuf"
                           :key="item.id"
                           :label="item.value"
                           :value="item.id">
                </el-option>
              </el-select>
            </span> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item label="时间段类型"
                        label-width="90px">
            <el-select v-model="queryForm.timeType"
                       placeholder="">
              <el-option v-for="item in timeType"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="开始时间">
            <el-date-picker v-model="queryForm.startTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm"
                            style="width: 100%"
                            :clearable="false"
                            placeholder="">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="结束时间">
            <el-date-picker v-model="queryForm.endTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm"
                            style="width: 100%"
                            :clearable="false"
                            placeholder="">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-button :disabled="$props.custom.editDisable"
                     @click="editRow"
                     type="primary">编辑</el-button>
          <el-button :disabled="$props.custom.reprintDisable"
                     @click="printCms"
                     type="primary">重印CMS</el-button>
          <el-button :disabled="$props.custom.nullifyDisable"
                     @click="invalid"
                     type="primary">作废</el-button>
          <el-button :disabled="$props.custom.exportDisable"
                     @click="exportList"
                     type="primary">导出</el-button>
        </el-col>
        <el-col :span="10">
          <el-form-item label=""
                        label-width="20px">
            <div style="float: right">
              <el-button @click="search"
                         type="primary">查询</el-button>
              <el-button @click="reset"
                         type="primary">重置</el-button>
              <el-button type="warning"
                         @click="logout">返回</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-col :span="24">
        <!-- @row-click="editRow" -->
        <el-table :data="tableData"
                  border
                  height="370px"
                  @selection-change="handleSelectionChange"
                  style="width: 100%">
          <el-table-column type="selection"
                           width="45">
          </el-table-column>
          <el-table-column type="index"
                           label="行号"
                           width="50">
          </el-table-column>
          <el-table-column align="center"
                           label="车牌"
                           width="100">
            <template slot-scope="scope">
              {{scope.row.tidNgenColor}} | {{scope.row.tidNgenPy}} | {{scope.row.tidNgenKey}} | {{scope.row.tidNgenSuf}}
            </template>
          </el-table-column>
          <el-table-column prop="tcCode"
                           align="center"
                           label="车卡号"
                           width="70">
          </el-table-column>
          <el-table-column align="center"
                           width="50"
                           label="卡号来源">
            <template slot-scope="scope">
              <span v-if="scope.row.hasPccCard">刷卡</span>
              <span v-else>人工输入</span>
            </template>
          </el-table-column>
          <el-table-column prop="idName"
                           align="center"
                           width="50"
                           label="司机姓名">
          </el-table-column>
          <el-table-column align="center"
                           width="80"
                           label="身份信息来源">
            <template slot-scope="scope">
              <span v-if="scope.row.hasIdCard">刷卡</span>
              <span v-else>人工输入</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           width="110"
                           label="进闸时间">
            <template slot-scope="scope">
              <span>{{formatDateTime(scope.row.gateinTime)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="manTel"
                           align="center"
                           width="80"
                           label="联系电话" />
          <el-table-column prop="companyName"
                           align="center"
                           width="80"
                           label="公司名称" />
          <el-table-column align="center"
                           width="110"
                           label="出闸时间">
            <template slot-scope="scope">
              <span>{{formatDateTime(scope.row.gateoutTime)}}</span>
            </template>
          </el-table-column>
          　
          <el-table-column align="center"
                           width="50"
                           label="作业状态">
            <template slot-scope="scope">
              <span v-if="scope.row.taskStatus === '01'">未出飞</span>
              <span v-if="scope.row.taskStatus === '02'">已出飞</span>
              <span v-if="scope.row.taskStatus === '03'">已出闸</span>
              <span v-if="scope.row.taskStatus === '04'">无效入闸</span>
            </template>
          </el-table-column>

          <el-table-column align="center"
                           width="50"
                           label="绑定类型">
            <template slot-scope="scope">
              <span v-if="scope.row.bindType === '01'">手工</span>
              <span v-if="scope.row.bindType === '02'">自助</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           width="50"
                           label="回执号">
            <template slot-scope="scope">
              <span>{{scope.row.returnReceiptId}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <!-- <el-col :span="14">&nbsp;</el-col> -->
      <el-col :span="24"
              style="text-align: center">
        <el-pagination background
                       layout="total,prev, pager, next"
                       @current-change="search"
                       :current-page.sync="queryForm.currentPage"
                       :page-size="10"
                       :total="queryForm.total">
        </el-pagination>
      </el-col>
    </el-row>
    <EditOsd ref="editOsd"
             @setForm="setParentForm"
             @customSentMqttMsg="customSentMqttMsg"
             @readCard="readCard"></EditOsd>

  </div>
</template>
<script>
const xlsx = require("node-xlsx")
const fs = require("fs")
import { GSAConstants } from '@/utils/access'
import { ipcRenderer } from 'electron'
import { formatDateTime, parseDate } from '@/utils/date'
import EditOsd from '../cms-v2/edit-osd.vue'
import {
  showWarningMsg,
  showSuccessMsg,
  log
} from '@/utils/message'

export default {
  components: { EditOsd },
  props: {
    custom: {
      type: Object,
      default: function () {
        return {}
      }
    },
    title: {
      type: String,
      default: function () {
        return ''
      }
    }, ic: {
      type: String,
      default: function () {
        return ''
      }
    },
    url: {
      type: String,
      default: function () {
        return ''
      }
    },
  },
  data () {
    return {
      path: '',
      showMessage: {
        msg: '请刷卡......',
        success: false,
        type: 'success',
        mession: '您的交柜未进行PAS申报(验箱的箱号未进行PAS申报)，请核查PAS申报资料',
        tips: '请不要在飞仔未打印完毕时拉扯飞仔纸,以免导致卡纸'
      },
      multipleSelection: [],
      tableData: [],
      msgInter: null,
      vehicleSuf: [
        { id: '', value: '' },
        { id: '港', value: '港' },
        { id: '澳', value: '澳' }
      ],
      vehicleColor: [
        { id: '', value: '' },
        { id: '蓝', value: '蓝' },
        { id: '黑', value: '黑' },
        { id: '绿', value: '绿' },
        { id: '红', value: '红' },
        { id: '黄', value: '黄' },
        { id: '白', value: '白' }
      ],
      timeType: [
        { id: '', value: '' },
        { id: '入闸时间', value: '入闸时间' },
        { id: '绑定时间', value: '绑定时间' }
      ],
      workStatus: [
        { id: '', value: '' },
        { id: '01', value: '未出飞' },
        { id: '02', value: '已出飞' },
        { id: '03', value: '已出闸' },
        { id: '04', value: '无效入闸' }
      ],
      bindStatus: [
        { id: '', value: '' },
        { id: '01', value: '未绑定' },
        { id: '02', value: '已绑定' },
        { id: '03', value: '作废' }
      ],
      bindType: [
        { id: '', value: '' },
        { id: '01', value: '手工' },
        { id: '02', value: '自助' }
      ],
      queryForm: {
        driverName: '',
        id: '',
        pcc: '',
        vehicleColor: '',
        vehiclePy: '',
        vehicleKey: '',
        startTime: '',
        endTime: '',
        bindStatus: '',
        taskStatus: '',
        bindType: '',
        timeType: '',
        currentPage: 1,
        total: 1
      },
      form: {
        name: '',
        idNo: '',
        saltIdNo: '',
        tractorNo: '',
        saltName: '',
        pccId: '',
        permitNo: '',
      }
    }
  },
  created () {
  },
  mounted () {
    this.init()
  },
  methods: {

    // 父页面加载完成会调用注册监听
    registerListener () {
      log('挂载选择文件夹监听事件')
      ipcRenderer.on('open-dir-check-dialog-reply', (event, path) => {
        this.path = path
        const qd = JSON.parse(JSON.stringify(this.queryForm))
        qd.pageSize = 9999
        let message = {
          dt: qd,
          ic: 'Export_EXCEL',
          en: false
        }
        log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.url, message)
        this.$emit('customSentMqttMsg', GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.url, message)
      })
    },
    init () {
      // 获取一周前日期
      let start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      start.setMinutes(0)
      start.setHours(0)
      this.queryForm.startTime = formatDateTime(start)

      let end = new Date();
      end.setMinutes(59)
      end.setHours(23)
      this.queryForm.endTime = formatDateTime(end)

      this.queryForm.timeType = '入闸时间'

    },
    // 转换日期
    formatDateTime (timestrap) {
      if (!timestrap) {
        return ''
      }
      return formatDateTime(new Date(timestrap))
    },
    // 生成excel的核心方法
    genExcel (path, data) {
      log('genEXCEL', data)

      const list = [
        {
          name: "sheet",
          data: this.getExportData(data)
        },
      ];

      const buffer = xlsx.build(list);
      fs.writeFile(path + '\\data_' + new Date().getTime() + '.xlsx', buffer, function (err) {
        if (err) {
          log(err, "保存excel出错");
        } else {
          log("写入excel成功!!!");
          showSuccessMsg('导出成功！')
        }
      })
    },
    // 导出
    exportList () {
      const startTime = parseDate(this.queryForm.startTime)
      const endTime = parseDate(this.queryForm.endTime)
      const startTime_ = startTime.getTime()
      const endTime_ = endTime.getTime()

      // 计算日期差
      const subTime = endTime_ - startTime_
      const subDays = subTime / (1000 * 3600 * 24)
      // 因为包含了小时, 结尾是23时，所以这里判断8
      if (subDays > 8) {
        showWarningMsg('查询时间必须在7天以内')
        return
      }

      if (this.tableData.length === 0) {
        showWarningMsg('请先进行查询')
        return
      }
      // 打开文件夹选择器， 选择后会通过事件回掉回来， 然后执行 genExcel
      this.browseFolder()
    },
    // 选中行
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    // 选择文件夹
    browseFolder () {
      ipcRenderer.send('open-dir-check-dialog')
    },
    // 获取导出数据
    getExportData (lists) {
      const data = []

      // 先存入表头
      data[0] = ['车牌', '车卡号', '卡号来源', '司机姓名', '身份信息来源', '进闸时间', '联系电话', '公司名称', '出闸时间', '作业状态', '绑定类型', '回执号']

      let i = 0
      lists.forEach(row => {
        const cardSouce = row.hasPccCard ? '刷卡' : '人工输入'
        const idSouce = row.hasIdCard ? '刷卡' : '人工输入'
        data[++i] = [
          row.tidNgenColor + '|' + row.tidNgenPy + '|' + row.tidNgenKey + '|' + row.tidNgenSuf,
          row.tcCode,
          cardSouce,
          row.idName,
          idSouce,
          this.formatDateTime(row.gateinTime),
          row.manTel,
          row.companyName,
          this.formatDateTime(row.gateoutTime),
          this.parseListName(this.workStatus, row.taskStatus),
          this.parseListName(this.bindType, row.bindType),
          row.returnReceiptId
        ]
      })

      return data
    },
    parseListName (list, id) {
      let obj = list.filter(item => item.id === id)[0]
      if (obj) {
        return obj.value
      }
    },
    // 执行请求
    customSentMqttMsg (url, message) {
      this.$emit('customSentMqttMsg', url, message)
    },
    // 作废
    invalid () {
      if (this.multipleSelection.length === 0) {
        showWarningMsg('最少选择一行需要被编辑的行')
        return
      }
      if (this.multipleSelection.length > 1) {
        showWarningMsg('最多只能编辑一行')
        return
      }
      const row = this.multipleSelection[0]
      const taskStatus = row.taskStatus
      const bindStatus = row.bindStatus
      if ('已出闸' === taskStatus) {
        showWarningMsg('此记录已出闸，不能作废')
        return;
      }

      if (bindStatus === '04' || bindStatus === '03') {
        showWarningMsg('此记录已作废')
        return
      }

      let message = {
        dt: {
          transId: row.transId
        },
        ic: GSAConstants().TOPIC_INVALID.ic,
        en: false
      }
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', GSAConstants().TOPIC_INVALID.url, message)
      this.$emit('customSentMqttMsg', GSAConstants().TOPIC_INVALID.url, message)
    },
    // 打印CMS
    printCms () {
      if (this.multipleSelection.length === 0) {
        showWarningMsg('最少选择一行需要被编辑的行')
        return
      }
      if (this.multipleSelection.length > 1) {
        showWarningMsg('最多只能编辑一行')
        return
      }
      const row = this.multipleSelection[0]


      //已出闸，无效入闸，作废的
      const taskStatus = row.taskStatus
      const bindStatus = row.bindStatus
      if (taskStatus === "03") {
        showWarningMsg('已出闸记录不能重印！')
        return;
      }
      if (taskStatus === "04") {
        showWarningMsg('无效入闸记录不能重印！')
        return;
      }

      if (bindStatus === '04' || bindStatus === '03') {
        showWarningMsg('已作废记录不能修改！')
        return
      }
      if (bindStatus === '01') {
        showWarningMsg('未绑定记录不能修改！')
        return
      }

      const fullTractorNo = row.tidNgenColor + '|' + row.tidNgenPy + '|' + row.tidNgenKey + '|' + row.tidNgenSuf

      let message = {
        dt: {
          nGenFullTractorNo: fullTractorNo
        },
        ic: GSAConstants().TOPIC_PRINT_CMS.ic,
        en: false
      }
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', GSAConstants().TOPIC_PRINT_CMS.url, message)
      this.$emit('customSentMqttMsg', GSAConstants().TOPIC_PRINT_CMS.url, message)
    },
    // 编辑行
    editRow () {
      if (this.multipleSelection.length === 0) {
        showWarningMsg('最少选择一行需要被编辑的行')
        return
      }
      if (this.multipleSelection.length > 1) {
        showWarningMsg('最多只能编辑一行')
        return
      }
      const row = this.multipleSelection[0]

      // // 校验
      if (row.taskStatus === '03') {
        showWarningMsg('已出闸记录不能修改！')
        return
      }
      if (row.taskStatus === '04') {
        showWarningMsg('无效入闸记录不能修改！')
        return
      }
      if (row.bindStatus === '04' || row.bindStatus === '03') {
        showWarningMsg('已作废记录不能修改！')
        return
      }
      if (row.bindStatus === '01') {
        showWarningMsg('未绑定记录不能修改！')
        return
      }


      log('检测到行被点击', row)
      const editForm = this.parseEditForm(row)
      log('转换行数据', editForm)
      // this.$store.commit('SET_CAR_EDIT_ROW', row)
      // console.log('测试从数据池中获取数据', this.$store.getters.carEditRow)
      this.$refs.editOsd.show(editForm)

      // 更新核心的数据包
      this.setParentForm(editForm)

      // 更新渲染页面
      this.setForm(editForm)

    },
    // 行数据转换成编辑表单需要的数据
    parseEditForm (row) {
      return {
        transid: row.transId,
        tcCode: row.tcCode,
        pccId: row.tcCode,
        permitNo: row.tcCode,
        companyName: row.companyName,
        returnReceiptId: row.returnReceiptId,
        //  "无PCC卡", "PCC卡已坏", "无效身份证", "使用第一代身份证", "使用港澳身份证",
        // "使用驾驶证", "使用从业资格证", "无任何证件", "其他" 
        reason: row.bindReason,
        hasPcc: row.hasPccCard,
        hasId: row.hasIdCard,
        idName: row.idName,
        manTel: row.manTel,
        driverCardId: row.idNumber,
        // "蓝", "黑", "绿", "红", "黄", "白"
        vehicleColor: row.tidNgenColor,
        vehiclePy: row.tidNgenPy,
        vehicleKey: row.tidNgenKey,
        // "", "港", "澳" 
        vehicleSuf: row.tidNgenSuf
      }
    },
    readCard (type) {
      this.$emit('readCard', type)
    },
    reset () {
      this.queryForm = {
        driverName: '',
        id: '',
        pcc: '',
        vehicleColor: '',
        vehiclePy: '',
        vehicleKey: '',
        startTime: '',
        endTime: '',
        bindStatus: '',
        taskStatus: '',
        bindType: '',
        timeType: '',
        currentPage: 1,
        total: 1
      }

      // 初始化 queryForm的参数
      this.init()
    },
    // search
    search () {
      const startTime = parseDate(this.queryForm.startTime)
      const endTime = parseDate(this.queryForm.endTime)
      const startTime_ = startTime.getTime()
      const endTime_ = endTime.getTime()


      // 计算日期差
      const subTime = endTime_ - startTime_

      if (subTime < 0) {
        showWarningMsg('查询结束时间必须大于开始时间')
        return
      }
      const subDays = subTime / (1000 * 3600 * 24)
      // 因为包含了小时, 结尾是23时，所以这里判断8
      if (subDays > 8) {
        showWarningMsg('查询时间必须在7天以内')
        return
      }

      let message = {
        dt: this.queryForm,
        ic: GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.ic,
        en: false
      }
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.url, message)
      this.$emit('customSentMqttMsg', GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.url, message)
    },
    // 连接MQTT回掉
    connectSuccess (res) {
      // 执行搜索
      this.search()
    },
    showMsg (dt) {
      this.showMessage.msg = dt.msg
      this.showMessage.type = dt.type
      let type = ''
      if (dt.type === 'error') {
        type = 'error'
      } else if (dt.type === 'green') {
        type = 'success'
      } else {
        type = 'info'
      }

      if (this.msgInter) {
        clearTimeout(this.msgInter)
      }
      this.msgInter = setTimeout(() => {
        this.$message({
          message: dt.msg,
          type: type
        })
      }, 1000)
    },
    setParentForm (form) {
      this.$emit('setForm', form)
    },
    logout () {
      this.$emit('logout')
    },
    // 读PCC卡回写的函数
    setForm (form) {
      this.$refs.editOsd.doMethod('setForm', form)
    },
    // 读ID成功
    readIcCardSuccess (res) {
      this.$refs.editOsd.doMethod('readIcCardSuccess', res)
    },
    // 读ID成功
    readIdCardSuccess (res) {
      this.$refs.editOsd.doMethod('readIdCardSuccess', res)
    },
    // mqtt 消息回掉
    handleSuccessMqttMessage (messageObject) {
      log('接收到系统返回数据， 准备渲染数据', JSON.stringify(messageObject))
      if (messageObject.ic === GSAConstants().TOPIC_GET_GATE_IN_TRACTOR_PAGE.ic) {

        let dt = messageObject.dt
        this.tableData = dt.data
        this.queryForm.currentPage = dt.currentPage
        this.queryForm.total = dt.total
      } else if (messageObject.ic === GSAConstants().TOPIC_PRINT_CMS.ic) {
        log('重印CMS成功')
        showSuccessMsg('重印CMS成功')
      } else if (messageObject.ic === GSAConstants().TOPIC_INVALID.ic) {
        showSuccessMsg('操作成功')
      } else if (messageObject.ic === 'Export_EXCEL') {
        let dt = messageObject.dt
        this.genExcel(this.path, dt.data)
      }
    },
  },
}
</script>

<style scoped>
.app-container >>> .el-input {
  font-size: 18px;
}

.app-container >>> .el-checkbox__inner {
  border: 1px solid #000000;
}
</style>
